# encoding: utf-8
"""
options.py

Created by Manel Rovira Trenc on 2008-06-01.
Copyright (c) 2008 __MyCompanyName__. All rights reserved.
"""

import sys
import os

from google.appengine.ext import db
import logging
import models




class Options(object):
    """docstring for Options"""
    def __init__(self):
        self._options = {}
        self._options.update(self.get_options())
        if len(self._options)==0:
            self.set_defaults()
    
    def set_defaults(self, initialize=True):
        """Create the default options"""
        self.new_option('blog_name', 'Blog Name', 'str', 'Blog name')
        self.new_option('analytics', 'Google Analytics Keys', 'str', '')
        self.new_option('blog_desc', 'Blog Description', 'str', 'Blog description')
        self.new_option('posts_per_page', 'Posts per page', 'int', '5')
        self.new_option('posts_per_feed', 'Posts per feed', 'int', '10')
        self.new_option('DEBUG', 'Debug', 'boolean', 'False')
        self.new_option('CACHE', 'Activate cache', 'boolean', 'True')
        self.new_option('sidebar_widgets', 'Sidebar widgets', 'list', '["categories" , "pages", "links", "feed"]','sidebar')
        if initialize:
             functions = __import__('functions')
             functions.init_blog()
            
        
    def get_options(self):
        """Read the options from the datastore and return a dict of options"""
        opts = models.Option.all()
        items = {}
        for opt in opts:
            items.update({opt.name: {'value': self.get_value(opt),
                                       'type': opt.option_type}
                          })
        return items
       
    def get_value(self, opt):
        """Get the value of the options"""
        if not opt.value:
            return None
        elif opt.option_type=="int":
            return int(opt.value)
        elif opt.option_type=="str":
            return opt.value
        elif opt.option_type=="boolean":
            if opt.value == 'True':
                return True
            else:
                return False
        elif opt.option_type=="list":
            try:
                list = eval(opt.value)
            except:
                return []
            if type(list) == type([]):
                return list
            else: 
                return []
    
    def check(self, value, opt_type):
        """Check if option value are valid for the option type given"""
        if opt_type == 'boolean':
            if value == 'True' or value == 'False':
                return
            return 'Invalid boolean value'
        elif opt_type == 'int':
            try:
                res = int(value)
            except:
                return 'Invalid integer'
            return
        elif opt_type == "list":
            try:
                alist = eval(value)
            except:
                return 'Invalid data format'
            if type(alist) == type([]):
                return
            else: 
                return 'Invalid data format'
        return 
      
    def set_option(self, name, value):
        """Set the option for a option"""  
        imp_models = __import__('models')
        imp_logging = __import__('logging')
        #imp_logging.error('%s %s' % (type(imp_models), type(models)))
        opt = imp_models.Option.all().filter('name',name).get()
        if not opt:
            return {'Error': 'Option not found'}
        if not value:
            opt.value = None
        else:
            err = self.check(value, opt.option_type)
            if err:
                return {opt.label: err}                 
            else:
                opt.value = value
        try:
            opt.put()
        except:
            return {'Error': 'Error saving option'}
        self._options.update({name: {'value':self.get_value(opt), 'type':opt.option_type} })
        return {}
    
    def new_option(self, name, label, option_type, value=None, space="global"):
        """Create a new option in the datastore"""
        if not self._options.has_key(name):
            opt = models.Option(name=name, label=label, option_type=option_type, space=space)
            if value:
                opt.value = value
            opt.put()
            self._options.update({name: {'value':self.get_value(opt), 'type':opt.option_type} })
    
    def options_list(self):
        """Return a list whith the options names"""
        return self._options.keys()   
        
    def __getattribute__(self, name):
        try:
            return object.__getattribute__(self,name)
        except AttributeError:
            dict = object.__getattribute__(self,'_options')
            if name=='dict':
                return dict
            if dict.has_key(name):
                return dict[name]['value']
            else:
                raise AttributeError



